package com.biubiushop.socket.netty;

import com.biubiushop.repository.IEquipmentRepository;
import com.biubiushop.repository.IOrdersRepository;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.nio.charset.Charset;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenjia
 * @date 2019/10/29
 **/
public class ServerFilter extends ChannelInitializer<SocketChannel> {

    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    private ConcurrentHashMap<String, Channel> channelMap;

    private IEquipmentRepository equipmentRepository;

    private IOrdersRepository ordersRepository;
    
    private StringRedisTemplate stringRedisTemplate;

    public ServerFilter(ThreadPoolTaskExecutor threadPoolTaskExecutor, ConcurrentHashMap<String, Channel> channelMap,
                        IEquipmentRepository equipmentRepository, IOrdersRepository ordersRepository, StringRedisTemplate stringRedisTemplate) {
        this.threadPoolTaskExecutor = threadPoolTaskExecutor;
        this.channelMap = channelMap;
        this.equipmentRepository = equipmentRepository;
        this.ordersRepository = ordersRepository;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline ph = ch.pipeline();
        // 以("\n")为结尾分割的 解码器
//        ByteBuf de = Unpooled.copiedBuffer("@@".getBytes());
//        ph.addLast("framer1", new DelimiterBasedFrameDecoder(1024, de));
//        ph.addLast("framer2", new FixedLengthFrameDecoder(20));
        // 解码和编码，应和客户端一致
        ph.addLast("decoder", new StringDecoder(Charset.forName("gbk")));
        ph.addLast("encoder", new StringEncoder(Charset.forName("gbk")));
        ph.addLast("handler", new ServerHandler(threadPoolTaskExecutor, channelMap,
                equipmentRepository, ordersRepository, stringRedisTemplate));// 服务端业务逻辑
    }
}
